import axios from "axios";
import React, { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { List } from "react-vant";
export interface ListState {
  id: string;
  title: string;
  image: string;
  word: string;
  price: number;
}

const Index: React.FC = () => {
  const [list, setList] = useState<ListState[]>([]);
  const [pageCode, setPageCode] = useState(1);
  const [finished, setFinished] = useState(false);
  const navigate = useNavigate();

  const fetchData = async () => {
    try {
      const resp = await axios.get("/api/list", { params: { pageCode } });
      const { data, code } = resp.data;
      if (code === 200) {
        setList([...list, ...data]);
        setPageCode(pageCode + 1);
      } else {
        setFinished(true);
      }
    } catch {
      console.log("请求数据报错！！！！");
    }
  };

  const toDetail = (v: ListState) => {
    navigate("/detail/" + v.id, { state: v });
  };

  // useEffect(() => {
  //   fetchData();
  // }, []);

  return (
    <div className="home">
      <List
        onLoad={fetchData}
        finished={finished}
        finishedText={"没有更多数据了"}
        loadingText="数据拼命加载中..."
      >
        <div className="list">
          {list.map((v) => {
            return (
              <dl key={v.id} onClick={() => toDetail(v)}>
                <dt>
                  <img src={v.image} alt="" />
                </dt>
                <dd>
                  <h3>{v.title}</h3>
                  <p className="word">{v.word}</p>
                  <p>
                    ￥：<span style={{ color: "red" }}>{v.price}</span>
                  </p>
                </dd>
              </dl>
            );
          })}
        </div>
      </List>
    </div>
  );
};

export default Index;
